package com.equipment.system.web.utils;


import java.util.HashMap;
import java.util.Map;

/**
 * Rest 对象,便捷的返回键值对给到前端.
 */
public class Rest extends HashMap<String, Object> {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Rest(final Builder builder) {
        putAll(builder.content);
        if (1 != builder.status) {
            put("status", builder.status);
        } else {
            remove("status");
        }
    }

    /**
     * 创建构造器,随后可以自由构造参数,然后调用 build() 完成构建.
     *
     * @return Builder
     */
    public static Builder newBuilder() {
        return new Builder();
    }

    /**
     * 构建器.
     */
    public static class Builder {

        private final Map<String, Object> content = new HashMap<>();
        private int status;

        /**
         * 私有化构造器,目的是希望固有对象构建方式.
         */
        private Builder() {
        }

        /**
         * 在根目录下添加键值对.
         *
         * @param key key
         * @param val val
         * @return Builder
         */
        public Builder put(final String key, final Object val) {
            content.put(key, val);
            return this;
        }

        /**
         * 添加一批键值对数据
         *
         * @param map map
         * @return Builder
         */
        public Builder putAll(final Map<String, Object> map) {
            content.putAll(map);
            return this;
        }

        /**
         * 与前端协定的状态码.
         *
         * @param val 状态码数值
         * @return Builder
         */
        public Builder status(final int val) {
            status = val;
            return this;
        }

        /**
         * 与前端协定的状态码.
         *
         * @param val 状态码,true=1,false=0
         * @return Builder
         */
        public Builder status(final boolean val) {
            status = val ? 1 : 0;
            return this;
        }

        /**
         * 完成对象构建.
         *
         * @return Rest
         */
        public Rest build() {
            return new Rest(this);
        }
    }
}
